//
//  CZPhotoView.swift
//  Weibo24
//
//  Created by apple on 16/3/7.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit
/*
    视图
    功能
*/
/*
    1. 视图三部曲
    2. 数据源方法, 设置一些属性(itemsize,)
    3. 定义一个数组,来存放图片
    4. 自定义cell-- 刷新数据,展示图片
    5. 删除按钮
    6. 添加按钮的功能
*/

let CZPhotoViewMargin: CGFloat = 10
let CZPhotoItmeMargin: CGFloat = 5

let  CZPhotoViewReuseIdentifier = "CZPhotoViewReuseIdentifier"

/*
    协议:
    声明一个协议 -> 声明代理方法 -> 声明一个代理属性 -> 遵守协议 -> 设置代理队形 -> 实现代理方法

*/


protocol CZPhotoCollecticonViewCellDelgate: NSObjectProtocol{

    //删除指定的图片
    func didRemoveIndexImage(index:Int)
    
    
}

class CZPhotoView: UICollectionView ,UICollectionViewDataSource,CZPhotoCollecticonViewCellDelgate,UICollectionViewDelegate{

    // 闭包属性
    var closure: (()->())?
    
    //定义一个数组,来存放图片
    // 私有的,
   private lazy var images: [UIImage] = [UIImage]()
    
    var flowLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        super.init(frame: frame, collectionViewLayout: flowLayout)
     
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    
    private func setupUI(){
    
        backgroundColor = UIColor.greenColor()
        
        //设置数据源代理
        dataSource = self
        
        delegate = self
        
        //注册cell
        registerClass(CZPhotoCollecticonViewCell.self, forCellWithReuseIdentifier: CZPhotoViewReuseIdentifier)
        
        //
        let ItemWH = (kUIScreenWidth - 2*CZPhotoViewMargin - 2*CZPhotoItmeMargin)/3
        flowLayout.itemSize = CGSizeMake(ItemWH, ItemWH)
        flowLayout.minimumInteritemSpacing = CZPhotoItmeMargin
        flowLayout.minimumLineSpacing = CZPhotoItmeMargin
        
    }
    
    //MARK:--对外公开一个方法
    func addImages(image: UIImage){
    
        images.append(image)
        //刷新数据
        reloadData()
    }
    
    
    //MARK:--对外提供一个方法,返回图片
    func allImages() ->[UIImage]{
    
        return images
        
    }
    deinit{
    
        printLog("photo 88")
        
    }
    //MARK:--懒加载
}

extension CZPhotoView{

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //先把特殊情况抛出
        if images.count == 0 || images.count == 9{
            //不显示 加号 按钮
            return images.count
        } else {
        
            return images.count + 1
        }
    }
    
    /*
        实际你选择了 5 张 ,但是 7个数据源
        数组越界的一个判断, 你就取 边界值 测试
    
    */
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CZPhotoViewReuseIdentifier, forIndexPath: indexPath) as! CZPhotoCollecticonViewCell
        
        //数组越界,就得判断
        if indexPath.item >= images.count {
            //越界
            // 赋值为nil,让它去实现 didSet方法 
            
            cell.iconImage = nil
        } else {
        
            cell.iconImage = images[indexPath.item]
        }
        
        
        //正向数据传递用 属性
        cell.indexPath = indexPath
        
        cell.delegate = self
        
        cell.backgroundColor = randomColor()
        
        return cell
    }
    
    //实现协议方法
    func didRemoveIndexImage(index: Int) {
        
        //删除指定的图片
        images.removeAtIndex(index)
        
        //刷新数据
        reloadData()
        
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        // 必须得是最后一个item点击的时候,再调用
        if indexPath.item == images.count {
            printLog("选择图片")
            
            //需要控制器去调用一下他自己的方法
            closure?()
        }
    }
}

//自定义cell
class CZPhotoCollecticonViewCell: UICollectionViewCell{

    weak var delegate: CZPhotoCollecticonViewCellDelgate?
    
    //定义一个属性
    var indexPath: NSIndexPath?
    
    //定义一个模型
    var iconImage: UIImage?{
    
        //didSet赋值之后会走
        
        didSet{
        
            if iconImage == nil {
                //显示加号
                iconImageView.image = UIImage(named: "compose_pic_add")
                
                deleteButton.hidden = true
            } else {
            
                //赋值
                iconImageView.image = iconImage
                
                deleteButton.hidden = false
            }
            
        }
        
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
    
     contentView.addSubview(iconImageView)
      contentView.addSubview(deleteButton)
        //设置约束
        iconImageView.frame = bounds
        
        deleteButton.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(contentView.snp_top)
            make.right.equalTo(contentView.snp_right)
        }
        
    }
    
    //
    @objc private func click(){
    
        printLog("删除")
        // 数据源里对应的那个图片删除
        // 缺少一个index
        // 获取下标
        if let index = indexPath?.item {
        
            delegate?.didRemoveIndexImage(index)
        }
    }
    
    //MARK:--懒加载
    
    private lazy var iconImageView: UIImageView = UIImageView()
    
    
    //删除按钮
    private lazy var deleteButton: UIButton = {
    
        let button = UIButton(type: UIButtonType.Custom)
    
        button.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "compose_card_delete_highlighted"), forState: UIControlState.Highlighted)
        
        //设置大小
        button.sizeToFit()
        
        // 添加点击事件
        button.addTarget(self, action: "click", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
    }()
}